package zhangcy.day0109.carlottery.dao.impl;

import zhangcy.day0109.carlottery.dao.UserDao;
import zhangcy.day0109.carlottery.po.User;
import zhangcy.day0109.carlottery.utils.BaseDao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class UserDaoImpl extends BaseDao implements UserDao {
    @Override
    public List<User> queryUserBy(Map<String, Object> map) {
        List<User> users = new ArrayList<>();
        User user = null;
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT U.ID, U.USER_NAME, U.MARK_NO, U.STATUS, U.PHONE, TO_CHAR(U.OPEN_DATE, 'yyyy-MM-dd') OPEN_DATE FROM T_USER U ");
        sql.append("  WHERE 1 = 1 ");
        if (map != null && map.size() > 0 ) {
            Object markNo = map.get("markNo");
            if (markNo != null) {
                sql.append(" AND U.MARK_NO LIKE ? ");
                rs = super.executeQuery(sql.toString(), new Object[]{ "%" + markNo + "%" });
            }
        }else{
            //查询所有
            //调用公共的查询方法
            rs = super.executeQuery(sql.toString());
        }
        try {
            while (rs.next()) {
                user = new User(rs.getInt("ID"), rs.getString("USER_NAME"),
                        rs.getString("MARK_NO"), rs.getInt("STATUS"),
                        rs.getString("PHONE"), rs.getString("OPEN_DATE"));
                users.add(user);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            super.closeAll(rs, pstmt, conn);
        }
        return users;
    }

    @Override
    public int insertUser(User user) {
        int addRes = 0;
        StringBuffer sql = new StringBuffer();
        sql.append(" INSERT INTO T_USER(ID,USER_NAME,MARK_NO,STATUS,PHONE,OPEN_DATE) ");
        sql.append("  VALUES (SEQ_T_USER_IDS.NEXTVAL,?,?,1,?,TO_DATE(?,'yyyy-MM-dd')) ");
        addRes = super.executeUpdate(sql.toString(), new Object[]{user.getUserName(), user.getMarkNo(),
                                user.getPhone(), user.getOpenDate()});
        return addRes;
    }
}
